package org.aaron.mp3player.service;

import org.aaron.mp3player.model.Mp3Info;
import org.aaron.mp3player.utils.DownloadHelper;
import org.aaron.mp3player.utils.FileUtils;
import org.aaron.mp3player.utils.SystemConfig;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

public class DownLoadService extends Service {

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		Log.d("DownLoadService", "onCreate");
		super.onCreate();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Mp3Info mp3Info = (Mp3Info) intent.getSerializableExtra("mp3info");
		Log.d("DownLoadService", "onStartCommand");
		new Thread(new DownloadThread(mp3Info)).start();
		return super.onStartCommand(intent, flags, startId);
	}

	@Override
	public void onDestroy() {
		Log.d("DownLoadService", "onDestroy");
		super.onDestroy();
	}

	class DownloadThread implements Runnable {
		private Mp3Info mp3Info;

		public DownloadThread(Mp3Info mp3Info) {
			this.mp3Info = mp3Info;
		}

		@Override
		public void run() {
			DownloadHelper downloadHelper = new DownloadHelper();
			int result = downloadHelper.downloadFile2Sd(SystemConfig.URL.WEB_SERVCE + mp3Info.getMp3Name(), "mp3/", mp3Info.getMp3Name());
			Log.d("DownloadThread  ", " run");
			Log.d("downloadFile2Sd  mp3 result", result + "");
			Looper.prepare();
			if (FileUtils.RESULT_SUCCESS == result) {
				Toast.makeText(DownLoadService.this, "下载成功", Toast.LENGTH_SHORT).show();
			} else if (FileUtils.RESULT_FILE_IS_EXIST == result) {
				Toast.makeText(DownLoadService.this, "文件已存在", Toast.LENGTH_SHORT).show();
			} else if (FileUtils.RESULT_FAIL == result) {
				Toast.makeText(DownLoadService.this, "下载失败", Toast.LENGTH_SHORT).show();
			}
			result = downloadHelper.downloadFile2Sd(SystemConfig.URL.WEB_SERVCE + mp3Info.getLrcName(), "mp3/", mp3Info.getLrcName());
			Log.d("downloadFile2Sd  lrc result", result + "");
			if (FileUtils.RESULT_SUCCESS == result) {
				Toast.makeText(DownLoadService.this, "下载成功", Toast.LENGTH_SHORT).show();
			} else if (FileUtils.RESULT_FILE_IS_EXIST == result) {
				Toast.makeText(DownLoadService.this, "文件已存在", Toast.LENGTH_SHORT).show();
			} else if (FileUtils.RESULT_FAIL == result) {
				Toast.makeText(DownLoadService.this, "下载失败", Toast.LENGTH_SHORT).show();
			}
			Looper.loop();
		}
	}

}
